home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: Strcat Doesn't work for this?
- Date: Sat, 13 Jan 96 13:54:10 GMT
- Organization: none
- Message-ID: <821541250snz@genesis.demon.co.uk>
- References: <Pine.SOL.3.91.960111151925.25068C-100000@lore.cs.purdue.edu>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <Pine.SOL.3.91.960111151925.25068C-100000@lore.cs.purdue.edu>
- cookca@cs.purdue.edu "** Craig Cook **" writes:
-
- >Here is my excerpt of code in question:
- >
- >
- >Putword(int w, char *imageChar)
- >{
- > w = (w & 0xff);
- > strcat( imageChar, (const char *)w );
- >
- >}
- >
- >Why does it core dump? It should work right?
-
- You seem to have some misconceptions about what casts do. A cast takes the
- *value* of its operand and tries to convert that value to the type specified
- in the cast. So (double)45 will take the integer value 45 and convert it
- to a double with the value 45 (or as close as possible). The C language
- doesn't explicitly define what happens when you cast an int to a pointer (
- except a constant expression with value 0 which is converted to a null
- pointer) - that is up to your implementation. Many implementation allow
- you create pointers to explicit memory locations using such a cast (e.g.
- (char *)45 creates a pointer value that points to a char at memory location
- 45), however you can't use this in portable C code. Maybe you were looking
- for something like the following:
-
- void Putword(int w, char *imageChar)
- {
- char *ptr = imageChar + strlen(imageChar);
-
- *ptr++ = w & 0xff;
- *ptr = '\0';
- }
-
- This actually results in undefined behaviour where char is equivalent to
- signed char and can't represent that value (w & 0xff). unsigned char
- may be a better choice in this code.
-
- Usually if you find yourself resorting to pointer casts you are taking
- the wrong approach.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-